package com.nhutcm.sms.receiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import com.nhutcm.sms.Utils.AppApplication;
import com.nhutcm.sms.Utils.LogUtils;
import com.nhutcm.sms.Utils.LogUtils.Level;
import com.nhutcm.sms.activity.MainActivity;
import com.nhutcm.sms.model.SMSClass;
import com.nhutcm.sms.network.SMSBroadcastingNetwork;
import com.nhutcm.sms.service.SMSBroadcastingService;

public class SMSBroadcastingReceiver extends BroadcastReceiver {

	private static String TAG = "SMSBroadcastingReceiver";
	public static String OK = "Ok";
	public static String FAILS = "Fail";

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		Log.i(TAG, arg1.getAction());
		Bundle b = arg1.getExtras();
		if (b == null) {
			if (arg1.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
				LogUtils.write(Level.ERROR, "BOOT_COMPLETED");
				Intent i = new Intent(arg0, MainActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				arg0.startActivity(i);
			}
			return;
		}

		if (arg1.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
			final Object[] pdusObj = (Object[]) b.get("pdus");
			for (int i = 0; i < pdusObj.length; i++) {
				SmsMessage currentMessage = SmsMessage
						.createFromPdu((byte[]) pdusObj[i]);
				String senderNum = currentMessage
						.getDisplayOriginatingAddress();
				String message = currentMessage.getDisplayMessageBody();
				SMSBroadcastingNetwork.forwardMessage(arg0, new SMSClass(
						senderNum, "", message));
			}

		} else if (arg1.getAction().equals("SMS_SENT")) {

			SMSClass sms = (SMSClass) b
					.getSerializable(SMSBroadcastingService.SMS_KEY);

			if (sms.getPhone().equals("") || sms.getSmsno().equals("")) {
				return;
			}

			Context context = ((AppApplication) arg0.getApplicationContext())
					.getCurrentCtx();
			MainActivity mActivity = (MainActivity) context;

			if (getResultCode() == Activity.RESULT_OK) {
				sms.setStatus(OK);
			} else {
				sms.setStatus(FAILS);
			}
			mActivity.onSMSResultCallback(sms);
		} else {
			Log.i(TAG, arg1.getAction());
		}

	}
}
